package com.itheima.reggie.contreller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;

import com.itheima.reggie.service.impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryContreller {

    @Autowired
    private CategoryServiceImpl categoryService;

    //新增品类
    @PostMapping
    public R<String> save(@RequestBody Category category){
      categoryService.save(category);
      return R.success("新增成功");
    }
    //查询品类
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //构造分页构造器
        Page<Category> categoryPage = new Page<>();

        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //根据sort进行排序
        queryWrapper.orderByDesc(Category::getSort);
        //分页查询
        categoryService.page(categoryPage,queryWrapper);
        return R.success(categoryPage);
    }

    //删除品类
    @DeleteMapping
    public R<String> delete(long id){
        categoryService.removeid(id);
        return R.success("删除成功");
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
    categoryService.updateById(category);
    return R.success("修改成功");
    }
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> QueryWrapper = new LambdaQueryWrapper<>();

        //添加条件
        QueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //添加排序条件
        QueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        List<Category> list = categoryService.list(QueryWrapper);
        return R.success(list);
    }
 }
